package com.xebest.web.service.impl;  

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.xebest.common.enums.erp.purch.VenAddTypeEnum;
import com.xebest.common.enums.erp.purch.VenPurchBillTypeEnum;
import com.xebest.common.enums.erp.purch.VenPurchCheckEnum;
import com.xebest.common.enums.erp.purch.VenPurchStatusEnum;
import com.xebest.common.enums.erp.purch.VenPurchTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptTypeEnum;
import com.xebest.common.enums.erp.sys.VenDelEnum;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.util.DateUtil;
import com.xebest.util.seq.PurchSeqUtil;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.form.XeVenPurchForm;
import com.xebest.web.form.XeVenPurchOrderBillForm;
import com.xebest.web.form.XeVenPurchProductForm;
import com.xebest.web.form.XeVenStoreReceiptForm;
import com.xebest.web.mapper.read.XeVenOrderReadMapper;
import com.xebest.web.mapper.read.XeVenPurchOrderReadMapper;
import com.xebest.web.mapper.read.XeVenPurchSupInfoReadMapper;
import com.xebest.web.mapper.read.XeVenStoreReceiptReadMapper;
import com.xebest.web.mapper.write.XeVenPurchOrderBillWriteMapper;
import com.xebest.web.mapper.write.XeVenPurchOrderDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenPurchOrderWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreInventoryWriteMapper;
import com.xebest.web.model.XeVenFinPurchPayDetailEntity;
import com.xebest.web.model.XeVenFinPurchPayEntity;
import com.xebest.web.model.XeVenPurchOrderBillEntity;
import com.xebest.web.model.XeVenPurchOrderDetailEntity;
import com.xebest.web.model.XeVenPurchOrderEntity;
import com.xebest.web.model.XeVenPurchSupInfoEntity;
import com.xebest.web.model.XeVenStoreInventoryEntity;
import com.xebest.web.model.XeVenStoreReceiptDetailEntity;
import com.xebest.web.model.XeVenStoreReceiptEntity;
import com.xebest.web.service.XeVenFinPurchPayReadService;
import com.xebest.web.service.XeVenPurchService;
import com.xebest.web.service.XeVenStoreInventoryService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.view.XeVenPurchOrderBillView;
import com.xebest.web.view.XeVenPurchProductView;
import com.xebest.web.view.XeVenPurchSupInfoView;
import com.xebest.web.view.XeVenPurchView;
import com.xebest.web.view.XeVenStoreReceiptView;
import com.xebest.web.view.XeVenSumPurchView;
import com.xebest.web.view.XeVenSummaryPurchView;

/**  
 * @desc: 采购相关业务实现类 
 * 
 * @author: 李书峰
 * @createTime: 2017年6月21日 下午3:14:57  
 * @history:  
 * @version: v1.0    
 */
@Service
public class XeVenPurchServiceImpl implements XeVenPurchService{
	
	private static final Logger log = LoggerFactory.getLogger(XeVenStoreRoleServiceImpl.class);//日志记录类
	 
	@Autowired
	private XeVenPurchOrderReadMapper xeVenPurchOrderReadMapper;//采购单主表读
	@Autowired
	private XeVenPurchOrderWriteMapper xeVenPurchOrderWriteMapper;//采购单主表写
	@Autowired
	private XeVenPurchOrderDetailWriteMapper xeVenPurchOrderDetailWriteMapper;//采购单详情写
	@Autowired
	private XeVenStoreReceiptService xeVenStoreReceiptService;//入库单业务层
	@Autowired
	private XeVenStoreInventoryService xeVenStoreInventoryService;//库存一览操作
	@Autowired
	private XeVenFinPurchPayReadService xeVenFinPurchPayReadService;//应付款单
	@Autowired
	private XeVenOrderReadMapper xeVenOrderReadMapper;//订单读
	@Autowired
	private XeVenPurchSupInfoReadMapper xeVenPurchSupInfoReadMapper;//供货商
	@Autowired
	private XeVenStoreInventoryWriteMapper xeVenStoreInventoryWriteMapper;//库存一览表
	@Autowired
	private XeVenPurchOrderBillWriteMapper xeVenPurchOrderBillWriteMapper;//单据插入
	@Autowired
	private XeBaseUtil xeBaseUtil ;
	@Autowired
	private XeVenStoreReceiptReadMapper  receiptReadMapper;//入库单读类
	
	/**
	 * 新增采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:39:08  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int insertPurchOrder(XeVenPurchForm xeVenPurchForm) throws Exception {
		//插入结果
		int resultSave = 0;
		//插入采购单结果
		int purchReult = 1;
		//插入采购详情结果
		int purchDetail = 1;
		//插入单据结果
		int billResult = 1;
		//判空
		XeVenPurchOrderEntity purchEntity = null ;
		if (null == xeVenPurchForm) 
			return resultSave;
		//对象转换
		purchEntity = JSONObject.parseObject(JSONObject.toJSONString(xeVenPurchForm), XeVenPurchOrderEntity.class);
//		purchEntity.setPurchOrder(PurchSeqUtil.seqUtils.createPurchOrder());
		purchEntity.setCreateUser(xeVenPurchForm.getModifyUser());
		purchEntity.setDelFlag(VenDelEnum.NO.getValue());
		purchEntity.setExpectedArrivalDate(DateUtil.toDay(xeVenPurchForm.getExpectedArrivalDate()));
		purchEntity.setSignDate(DateUtil.toDay(xeVenPurchForm.getSignDate()));
		//插入采购单
		purchReult = xeVenPurchOrderWriteMapper.insertPurch(purchEntity);
		//插入采购单详情
		List<XeVenPurchProductForm> productFormList = xeVenPurchForm.getPurchProductList();
		if(null != productFormList && productFormList.size() > 0 && purchReult > 0 ){
			//form转entity
			List<XeVenPurchOrderDetailEntity> detailEntityList = new ArrayList<XeVenPurchOrderDetailEntity>();
			for(XeVenPurchProductForm form:productFormList){
				form.setPurchOrder(purchEntity.getPurchOrder());
				XeVenPurchOrderDetailEntity product = JSONObject.parseObject(JSONObject.toJSONString(form), XeVenPurchOrderDetailEntity.class);
				product.setUserCode(purchEntity.getUserCode());
				detailEntityList.add(product);
			}
			purchDetail = xeVenPurchOrderDetailWriteMapper.insertPurchProductBatch(detailEntityList);
		}
		
		List<XeVenPurchOrderBillForm> billFormList = xeVenPurchForm.getBillList();
		if(null != billFormList && billFormList.size() > 0 && purchReult > 0 ){
			List<XeVenPurchOrderBillEntity> billEntityList = new ArrayList<XeVenPurchOrderBillEntity>();
			for(XeVenPurchOrderBillForm bill:billFormList){
				if(VenPurchBillTypeEnum.BILL_ENTRY.getValue().equals(bill.getBillType())){
					bill.setBillCode(PurchSeqUtil.seqUtils.createBgdCode());
					bill.setBillName(VenPurchBillTypeEnum.BILL_ENTRY.getName());
				}else if(VenPurchBillTypeEnum.BILL_PRATIQUE.getValue().equals(bill.getBillType())){
					bill.setBillCode(PurchSeqUtil.seqUtils.createJyzCode());
					bill.setBillName(VenPurchBillTypeEnum.BILL_PRATIQUE.getName());
				}else if(VenPurchBillTypeEnum.BILL_PURCH_CONTRACT.getValue().equals(bill.getBillType())){
					bill.setBillCode(PurchSeqUtil.seqUtils.createHtCode());
					bill.setBillName(VenPurchBillTypeEnum.BILL_PURCH_CONTRACT.getName());
				}
				bill.setPurchOrder(purchEntity.getPurchOrder());
				bill.setModifyUser(xeVenPurchForm.getModifyUser());
				bill.setCreateUser(xeVenPurchForm.getModifyUser());
				XeVenPurchOrderBillEntity billEntity = JSONObject.parseObject(JSONObject.toJSONString(bill), XeVenPurchOrderBillEntity.class);
				billEntityList.add(billEntity);
			}
			billResult = xeVenPurchOrderBillWriteMapper.insertBillBatch(billEntityList); 
		}
		log.debug("采购单更新结果："+purchReult+"，采购详情更新结果："+purchDetail+"采购单据更新结果："+billResult);
		resultSave = purchReult > 0 && purchDetail > 0 ? 1 : 0; 
		if( 0 == resultSave){
			purchEntity.setDelFlag(VenDelEnum.YES.getValue());
			xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
		}
		return resultSave;  
	}
	
	/**
	 * 编辑采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:39:08  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int updatePurchOrder(XeVenPurchForm xeVenPurchForm) throws Exception {
		//插入结果
		int resultSave = 0;
		//插入采购单结果
		int purchReult = 1;
		//插入采购详情结果
		int purchDetail = 1;
		//插入单据结果
		int billResult = 1;
		//判空
		XeVenPurchOrderEntity purchEntity = null ;
		if (null == xeVenPurchForm) 
			return resultSave;
		//对象转换
		purchEntity = JSONObject.parseObject(JSONObject.toJSONString(xeVenPurchForm), XeVenPurchOrderEntity.class);
		List<String> purchOrderList = new ArrayList<String>();
		if(StringUtils.isNotBlank(xeVenPurchForm.getPurchOrder())){
			purchOrderList.add(xeVenPurchForm.getPurchOrder());
			purchEntity.setPurchOrderList(purchOrderList);
		}
		//更新采购单
		purchReult = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
		
		//插入新采购单详情
		List<XeVenPurchProductForm> productFormList = xeVenPurchForm.getPurchProductList();
		if( null != productFormList && productFormList.size() > 0 && purchReult > 0 ){
			//删除旧采购单详情
			XeVenPurchOrderDetailEntity del = new XeVenPurchOrderDetailEntity();
			del.setDelFlag(VenDelEnum.YES.getValue());
			del.setPurchOrderList(purchOrderList);
			xeVenPurchOrderDetailWriteMapper.updatePurchProduct(del);
			//插入新采购单详情
			List<XeVenPurchOrderDetailEntity> detailEntityList = new ArrayList<XeVenPurchOrderDetailEntity>();
			for(XeVenPurchProductForm detail :productFormList){
				XeVenPurchOrderDetailEntity product = JSONObject.parseObject(JSONObject.toJSONString(detail), XeVenPurchOrderDetailEntity.class);
				detailEntityList.add(product);
			}
			purchDetail = xeVenPurchOrderDetailWriteMapper.insertPurchProductBatch(detailEntityList);
		}
		//删除旧的采购单单据
		if(StringUtils.isBlank(xeVenPurchForm.getOrderId())){
			XeVenPurchOrderBillEntity oldBill = new XeVenPurchOrderBillEntity();
			oldBill.setDelFlag(VenDelEnum.YES.getValue());
			oldBill.setModifyUser(xeVenPurchForm.getModifyUser());
			oldBill.setPurchOrderList(purchOrderList);
			xeVenPurchOrderBillWriteMapper.updateBill(oldBill);
			List<XeVenPurchOrderBillForm> billFormList = xeVenPurchForm.getBillList();
			if(null != billFormList && billFormList.size() > 0 && purchReult > 0 ){
				//插入新采购单单据
				List<XeVenPurchOrderBillEntity> billEntityList = new ArrayList<XeVenPurchOrderBillEntity>();
				for(XeVenPurchOrderBillForm bill:billFormList){
					if(VenPurchBillTypeEnum.BILL_ENTRY.getValue().equals(bill.getBillType())){
						bill.setBillCode(PurchSeqUtil.seqUtils.createBgdCode());
						bill.setBillName(VenPurchBillTypeEnum.BILL_ENTRY.getName());
					}else if(VenPurchBillTypeEnum.BILL_PRATIQUE.getValue().equals(bill.getBillType())){
						bill.setBillCode(PurchSeqUtil.seqUtils.createJyzCode());
						bill.setBillName(VenPurchBillTypeEnum.BILL_PRATIQUE.getName());
					}else if(VenPurchBillTypeEnum.BILL_PURCH_CONTRACT.getValue().equals(bill.getBillType())){
						bill.setBillCode(PurchSeqUtil.seqUtils.createHtCode());
						bill.setBillName(VenPurchBillTypeEnum.BILL_PURCH_CONTRACT.getName());
					}
					bill.setPurchOrder(purchEntity.getPurchOrder());
					bill.setModifyUser(xeVenPurchForm.getModifyUser());
					bill.setCreateUser(xeVenPurchForm.getModifyUser());
					XeVenPurchOrderBillEntity billEntity = JSONObject.parseObject(JSONObject.toJSONString(bill), XeVenPurchOrderBillEntity.class);
					billEntityList.add(billEntity);
				}
				billResult = xeVenPurchOrderBillWriteMapper.insertBillBatch(billEntityList); 
			}
		}
		log.debug("采购单更新结果："+purchReult+"，采购详情更新结果："+purchDetail+"采购单据更新结果："+billResult);
		resultSave = purchReult > 0 && purchDetail > 0 ? 1 : 0; 
		return resultSave;  
	}
	
	/**
	 * 确认收货入库
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:39:08  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int updateGoodsReceipt(XeVenPurchForm xeVenPurchForm) throws Exception {
		//插入结果
		int resultSave = 0;
		
		//判空
		if (null == xeVenPurchForm || null == xeVenPurchForm.getPurchOrder()) 
			return resultSave;
		
		//查询之前的批次总数量（原实际入库数），在计划采购数可以大于实际入库数情况下，可以对采购单多次入库（根据采购单状态即可）
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userCode", xeVenPurchForm.getUserCode());
//		map.put("userCode", "SH170712925781");
		map.put("purchOrder", xeVenPurchForm.getPurchOrder());
//		List<String> purchOrderList = new ArrayList<String>();
//		purchOrderList.add(xeVenPurchForm.getPurchOrder());
//		map.put("purchOrderList", purchOrderList);
		List<XeVenPurchOrderEntity> purchList = xeVenPurchOrderWriteMapper.queryPurchDetail(map);

		//集采采购中采购单才能收货入库
		XeVenPurchOrderEntity purch = null;
		if(null != purchList && purchList.size() > 0){
			 purch = purchList.get(0);
			if( !VenPurchStatusEnum.PURCHING.getValue().equals(purch.getPurchStatus())
				  || !VenPurchTypeEnum.LARGE_BUY.getValue().equals(purch.getPurchType())){
				resultSave = 200;
				return resultSave;
			}
		}
		//查询采购详情
		List<XeVenPurchOrderDetailEntity> detailList = xeVenPurchOrderDetailWriteMapper.queryPurchProductList(map);
		
		//判断是否已入库完成
		List<XeVenPurchProductView> arrives = xeVenPurchOrderWriteMapper.queryPurchArriveProductList(map);
		if( null != detailList && detailList.size() > 0
				&& null != arrives && arrives.size() > 0 
				){
			int proNum = 0;//已完成收货的sku
			for(XeVenPurchOrderDetailEntity viewOne:detailList){
				for(XeVenPurchProductView viewTwo:arrives){
					if(null == viewTwo || StringUtils.isBlank(viewTwo.getPurchOrder())){
						continue;
					}
					if(viewOne.getProSku().equals(viewTwo.getProSku())
						&& null != viewOne.getProNum()){
						if(null != viewTwo.getArriveNum()
							&& (viewTwo.getArriveNum().compareTo(viewOne.getProNum()) > 0 
									||viewTwo.getArriveNum().compareTo(viewOne.getProNum()) == 0 )){
							proNum = proNum+1;
						}else{
							break;
						}
					}
					
				}
			}
			if(proNum == detailList.size()){
				resultSave = 300;
				return resultSave;
			}
		}
		
		//假设保存结果 
		resultSave = 1;
		
		//调出本次要插入批次
		List<XeVenPurchProductForm> productFormList = xeVenPurchForm.getPurchProductList();
		
/*		对符合条件的进行入库（因为实际入库数可以大于计划采购数，一个采购单多个商品，一个商品已经达到计划入库数，其他商品还没有。此时如果要
		该商品前、7继续填写入库，该商品的数量是否再加，可以再加）*/
		//集采生成入库单及入库明细，释放采购在途数，增加库存，更新采购单状态。
		if(null != productFormList && productFormList.size() > 0
				&& null != detailList && detailList.size() > 0 ){
			//生成入库单
			XeVenStoreReceiptEntity storeReceipt = new XeVenStoreReceiptEntity();
			storeReceipt.setCreateUser(xeVenPurchForm.getModifyUser());
			storeReceipt.setModifyUser(xeVenPurchForm.getModifyUser());
			storeReceipt.setReceiptType(VenStoreReceiptTypeEnum.CG_RECEIPT.getValue());
			storeReceipt.setRelationOrder(xeVenPurchForm.getPurchOrder());
			storeReceipt.setRemark(purch.getRemark());
			storeReceipt.setStoreId(purch.getStoreId());
			storeReceipt.setStoreName(purch.getStoreName());
			storeReceipt.setUserCode(xeVenPurchForm.getUserCode());
			
			//生成入库单明细
			List<XeVenStoreReceiptDetailEntity>	receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();
			for(XeVenPurchOrderDetailEntity entity : detailList){
				XeVenStoreReceiptDetailEntity detail = new XeVenStoreReceiptDetailEntity();
				for(XeVenPurchProductForm form : productFormList){
					if(form.getProSku().equals(entity.getProSku())){
						detail.setCurrentInNum(form.getCurArriveNum());
						continue;
					}
				}
				if(null == detail.getCurrentInNum() ){
					continue;
				}
				detail.setProNum(entity.getProNo());
				detail.setProCategoryId(entity.getCategoryCode());
				detail.setBatchPrice(entity.getBuyPrice());
				detail.setCreateUser(purch.getModifyUser());
				detail.setModifyUser(purch.getModifyUser());
				detail.setPlanInNum(entity.getProNum());
				detail.setProCategoryName(entity.getCategoryName());
				detail.setProName(entity.getProName());
				detail.setProMainImg(entity.getPicUrl());
				detail.setProPricingType(entity.getPriceType());
				detail.setProSepcValue(entity.getSpecValue());
				detail.setProSpecName(entity.getSpecName());
				detail.setProSku(entity.getProSku());
				detail.setProUnit(entity.getProUnit());
				detail.setRemark(entity.getRemark());
				detail.setCreateUser(xeVenPurchForm.getModifyUser());
				receiptDetailList.add(detail);
			}
			storeReceipt.setReceiptDetailList(receiptDetailList);
			storeReceipt.setVersion(xeVenPurchForm.getVersion());
			//保存入库单
			resultSave = xeVenStoreReceiptService.saveStoreReceipt(storeReceipt);
		}
		return resultSave;  
	}
	
	/**
	 * （假）删除采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:39:08  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public Map<String,Object> deletePurchOrder(List<XeVenPurchForm> xeVenPurchFormList) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();  
		if( null == xeVenPurchFormList || xeVenPurchFormList.size() == 0){
			map.put("msg", "失败原因为未选中任何数据");
			map.put("successSize", 0);
			map.put("failSize", 0);
			map.put("totalSize", 0);
			return map; 
		}
		//删除结果
		int resultSave = 0;
		StringBuilder msgBuilder = new StringBuilder("失败采购单code如下：");
		//更新采购单
		List<String> purchOrderList = new ArrayList<String>();
		List<String> purchOrderSingle = new ArrayList<String>();
		for(XeVenPurchForm form : xeVenPurchFormList){
			XeVenPurchOrderEntity purchEntity = JSONObject.parseObject(JSONObject.toJSONString(form), XeVenPurchOrderEntity.class);
			purchEntity.setDelFlag(VenDelEnum.YES.getValue());
			purchEntity.setModifyUser(xeVenPurchFormList.get(0).getModifyUser());
			purchOrderSingle.add(form.getPurchOrder());
			purchEntity.setPurchOrderList(purchOrderSingle);
			purchEntity.setPurchOrder(null);
			int updateInt = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
			if(updateInt == 0){
				msgBuilder.append(form.getSupplierCode()).append(",");
			}else{
				purchOrderList.add(form.getPurchOrder());
			}
			resultSave = resultSave + updateInt;
		}
		
		//删除采购单详情
		XeVenPurchOrderDetailEntity del = new XeVenPurchOrderDetailEntity();
		del.setDelFlag(VenDelEnum.YES.getValue());
		del.setPurchOrderList(purchOrderList);
		int purchDetail = xeVenPurchOrderDetailWriteMapper.updatePurchProduct(del);
		
		int totalSize = xeVenPurchFormList.size();
		map.put("msg", msgBuilder.substring(0, msgBuilder.length()-1).toString());
		map.put("successSize", resultSave);
		map.put("failSize", totalSize - resultSave);
		map.put("totalSize", totalSize);
		
		log.debug("采购单更新结果："+resultSave+"，采购详情更新结果："+purchDetail);
		//resultSave = resultSave > 0 && purchDetail > 0 ? 1 : 0; 
		return map;  
	}
	  
	/**
	 * 采购审核采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:42:48  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public Map<String,Object> purchCheck(List<XeVenPurchForm> xeVenPurchFormList) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();  
		if( null == xeVenPurchFormList || xeVenPurchFormList.size() == 0){
			map.put("msg", "失败原因为未选中任何数据");
			map.put("successSize", 0);
			map.put("failSize", 0);
			map.put("totalSize", 0);
			return map; 
		}
		//更新采购单结果
		int resultCheck = 0;
		StringBuilder msgBuilder = new StringBuilder("失败采购单code如下：");

		//更新审核状态和采购状态
		for(XeVenPurchForm form : xeVenPurchFormList){
			XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
			List<String> purchOrderList = new ArrayList<String>();
			purchEntity.setPurchStatus(xeVenPurchFormList.get(0).getPurchStatus());
			purchEntity.setCheckStatus(xeVenPurchFormList.get(0).getCheckStatus());
			purchEntity.setModifyUser(xeVenPurchFormList.get(0).getModifyUser());
			purchEntity.setVersion(form.getVersion());
			purchOrderList.add(form.getPurchOrder());
			purchEntity.setPurchOrderList(purchOrderList);
			purchEntity.setUserCode(form.getUserCode());
			purchEntity.setPurchExamineRemark(form.getPurchExamineRemark());
			int updateInt = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
			if(updateInt == 0){
				msgBuilder.append(form.getPurchOrder()).append(",");
			}
			resultCheck = resultCheck + updateInt;
		}
		
		int totalSize = xeVenPurchFormList.size();
		map.put("msg", msgBuilder.substring(0, msgBuilder.length()-1).toString());
		map.put("successSize", resultCheck);
		map.put("failSize", totalSize - resultCheck);
		map.put("totalSize", totalSize);
		
		log.debug("采购单更新结果："+resultCheck);
		return map ;  
	}
	
	/**
	 * 鲜咨达审核采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:42:48  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public Map<String,Object> xianCheck(List<XeVenPurchForm> xeVenPurchFormList) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();  
		if( null == xeVenPurchFormList || xeVenPurchFormList.size() == 0){
			map.put("msg", "失败原因为未选中任何数据");
			map.put("successSize", 0);
			map.put("failSize", 0);
			map.put("totalSize", 0);
			return map; 
		}
		//更新采购单结果
		int resultCheck = 0;
		StringBuilder msgBuilder = new StringBuilder("失败采购单code如下：");

		//更新审核状态和采购状态
		for(XeVenPurchForm form : xeVenPurchFormList){
			XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
			List<String> purchOrderList = new ArrayList<String>();
			purchEntity.setPurchStatus(xeVenPurchFormList.get(0).getPurchStatus());
			purchEntity.setCheckStatus(xeVenPurchFormList.get(0).getCheckStatus());
			purchEntity.setModifyUser(xeVenPurchFormList.get(0).getModifyUser());
			purchEntity.setVersion(form.getVersion());
			purchOrderList.add(form.getPurchOrder());
			purchEntity.setPurchOrderList(purchOrderList);
			purchEntity.setUserCode(form.getUserCode());
			purchEntity.setXianExamineRemark(form.getXianExamineRemark());
			int updateInt = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
			if(updateInt == 0){
				msgBuilder.append(form.getPurchOrder()).append(",");
			}
			resultCheck = resultCheck + updateInt;
		}
		
		int totalSize = xeVenPurchFormList.size();
		map.put("msg", msgBuilder.substring(0, msgBuilder.length()-1).toString());
		map.put("successSize", resultCheck);
		map.put("failSize", totalSize - resultCheck);
		map.put("totalSize", totalSize);
		
		log.debug("采购单更新结果："+resultCheck);
		return map ;  
	}
	
	/**
	 * 财务审核采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:42:48  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public Map<String,Object> financeCheck(List<XeVenPurchForm> xeVenPurchFormList) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();  
		if( null == xeVenPurchFormList || xeVenPurchFormList.size() == 0){
			map.put("msg", "失败原因为未选中任何数据");
			map.put("successSize", 0);
			map.put("failSize", 0);
			map.put("totalSize", 0);
			return map; 
		}
		//更新采购单结果
		int resultCheck = 0;
		StringBuilder msgBuilder = new StringBuilder("失败采购单code如下：");
		List<String> purchOrderList = new ArrayList<String>();
		//更新审核状态和采购状态
		for(XeVenPurchForm form : xeVenPurchFormList){
			XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
			List<String> purchOrderSingle = new ArrayList<String>();
			purchOrderSingle.add(form.getPurchOrder());
			purchEntity.setPurchOrderList(purchOrderSingle);
			purchEntity.setPurchStatus(form.getPurchStatus());
			purchEntity.setCheckStatus(form.getCheckStatus());
			purchEntity.setModifyUser(form.getModifyUser());
			purchEntity.setUserCode(form.getUserCode());
			purchEntity.setVersion(form.getVersion());
			purchEntity.setFinanceExamineRemark(form.getFinanceExamineRemark());
			int updateCheck = xeVenPurchOrderWriteMapper.updatePurch(purchEntity); 
			if(updateCheck == 0){
				msgBuilder.append(form.getPurchOrder()).append(",");
			}
			resultCheck = resultCheck + updateCheck;
			purchOrderList.add(form.getPurchOrder());
		}
		int totalSize = xeVenPurchFormList.size();
		map.put("msg", msgBuilder.substring(0, msgBuilder.length()-1).toString());
		map.put("successSize", resultCheck);
		map.put("failSize", totalSize - resultCheck);
		map.put("totalSize", totalSize);
		log.debug("采购单更新结果："+resultCheck);
		
		//查询采购相关数据
		Map<String,Object> mapParms = new HashMap<String,Object>();
		String userCode = xeVenPurchFormList.get(0).getUserCode();
		String userName = xeVenPurchFormList.get(0).getModifyUser();
		mapParms.put("userCode",userCode);
		mapParms.put("purchOrderList", purchOrderList);
		List<XeVenPurchOrderEntity> purchList = xeVenPurchOrderWriteMapper.queryPurchDetail(mapParms);
		List<XeVenPurchOrderDetailEntity> detailList = xeVenPurchOrderDetailWriteMapper.queryPurchProductList(mapParms);
		//财务审核之后库存初始化集采商品，因为集采商品可能不存在
		if(VenPurchCheckEnum.CHECKED.getValue().equals(xeVenPurchFormList.get(0).getCheckStatus())
			&& VenPurchStatusEnum.PURCHING.getValue().equals(xeVenPurchFormList.get(0).getPurchStatus())){
			//更新采购在途数
			if( null != purchList && purchList.size() > 0 
				&& null != detailList && detailList.size() > 0){
				for(XeVenPurchOrderEntity purch : purchList ){
					//零采分拨不要更新 
					if(!VenPurchTypeEnum.LARGE_BUY.getValue().equals(purch.getPurchType())){
						continue;
					}
					for(XeVenPurchOrderDetailEntity entity : detailList){
						XeVenStoreInventoryEntity storeInventory = new XeVenStoreInventoryEntity();
						storeInventory.setUserCode(userCode);
						storeInventory.setStoreId(purch.getStoreId());
						storeInventory.setProSku(entity.getProSku());
						/**
						 * 添加商品的基本信息 dcj 修改 start
						 */
						storeInventory.setProNum(entity.getProNo());
						storeInventory.setProMainImg(entity.getPicUrl());
						storeInventory.setProName(entity.getProName());
						storeInventory.setProCategoryId(entity.getCategoryCode());
						storeInventory.setProCategoryName(entity.getCategoryName());
						storeInventory.setProPricingType(entity.getPriceType());
						storeInventory.setProUnit(entity.getProUnit());
						storeInventory.setProSpecName(entity.getSpecName());
						storeInventory.setProSepcValue(entity.getSpecValue());
						storeInventory.setFrozenFlag(entity.getFrozenFlag());
						storeInventory.setCreateUser(purch.getCreateUser());
						storeInventory.setTransitInv(entity.getProNum());
						/**
						 * 添加商品的基本信息 dcj 修改 end
						 */
						storeInventory.setModifyUser(userName);
						xeVenStoreInventoryService.initStoreInv(storeInventory);
					}
				}
				/**
				 * 2017/11/1 11:11
				 * 毕总需求更改，应付款单从财务审核结束之后改到发货时生成
				 */
				
//				//生成应付款单(2017nian 11yue )
//				Map<String,String> mapFin = new HashMap<String,String>();
//				for(XeVenPurchOrderEntity purch : purchList ){
//					if(mapFin.containsKey(purch.getPurchOrder())){
//						String value = mapFin.get(purch.getPurchOrder()).toString();
//						mapFin.put(purch.getPurchOrder(), value+","+purch.getOrderId());
//					}else{
//						mapFin.put(purch.getPurchOrder(), purch.getOrderId());
//					}
//				}
//				
//				List<XeVenFinPurchPayEntity> payList = new ArrayList<XeVenFinPurchPayEntity>();
//				Map<String,String> purPayMap = new HashMap<String,String>();
//				for(XeVenPurchOrderEntity purch : purchList ){
//					if(VenPurchTypeEnum.LARGE_BUY.getValue().equals(purch.getPurchType())){
//						//一期应付款单只生成零采的
//						//一期二版改成零采+分拨
//						continue;
//					}
//					if(purPayMap.containsKey(purch.getPurchOrder())){
//						continue;
//					}
//					XeVenFinPurchPayEntity fi = new XeVenFinPurchPayEntity();
//					fi.setUserCode(userCode);//用户编码
//					fi.setpSettleCode(StoreHouseSeqUtil.seqUtils.createFinPurchCode());//付款单号
//					fi.setPurchId(purch.getPurchOrder());//采购单号
//					fi.setOrderId(mapFin.get(purch.getPurchOrder()));//订单号
//					fi.setpSettleStatus(1);
//					fi.setRejectStatus(1);
//					fi.setCreateUser(xeVenPurchFormList.get(0).getModifyUser());
//					fi.setDelFlag(VenDelEnum.NO.getValue());
//					fi.setFinType(1);
//					payList.add(fi);
//					purPayMap.put(purch.getPurchOrder(), fi.getpSettleCode());
//				}
//				if(null != payList && payList.size() > 0 ){
//					xeVenFinPurchPayReadService.insertBatchFinPurchPay(payList);
//				}
//				
//				List<XeVenFinPurchPayDetailEntity> finPurchPayDetailList = new ArrayList<XeVenFinPurchPayDetailEntity>();
//				for(XeVenPurchOrderDetailEntity entity : detailList){
//					if(!purPayMap.containsKey(entity.getPurchOrder())){
//						continue;
//					}
//					XeVenFinPurchPayDetailEntity detail = new XeVenFinPurchPayDetailEntity();
//					detail.setpSettleCode(purPayMap.get(entity.getPurchOrder()));//付款单号
//					detail.setProSku(entity.getProSku());
//					detail.setProName(entity.getProName());
//					detail.setProNum(entity.getProNo());
//					detail.setSpecName(entity.getSpecName());
//					detail.setSpecValue(entity.getSpecValue());
//					detail.setPricingType(entity.getPriceType());
//					detail.setProUnit(entity.getProUnit());
//					detail.setPurchNum(entity.getProNum());
//					detail.setBuyPrice(entity.getBuyPrice());//进货价
//					detail.setPurchPrice(entity.getProAmount());//采购单价*采购数量
//					detail.setProOrgCode(entity.getCategoryCode());
//					detail.setProOrgCodeName(entity.getCategoryName());
//					detail.setRealSendNum(entity.getRealSendNum());
//					detail.setProCostPrice(entity.getProCostPrice());
//					detail.setProPrice(entity.getProPrice());
//					detail.setProPayAmount(entity.getProPayAmount());
//					detail.setDifferenceRefAmount(entity.getDifferenceAmount());
//					finPurchPayDetailList.add(detail);
//				}
//				if(null != finPurchPayDetailList && finPurchPayDetailList.size() > 0 ){
//					xeVenFinPurchPayReadService.insertBatchFinPurchPayDetail(finPurchPayDetailList);
//				}
			}
			
		}
		
/*		//记录条数（观察是否继续需要）
		if(null != detailList && detailList.size() > 0){

			List<XeVenPurchSupProductEntity> productList = new ArrayList<XeVenPurchSupProductEntity>();
			for(XeVenPurchOrderDetailEntity entity : detailList){ 
				XeVenPurchSupProductEntity product = new XeVenPurchSupProductEntity();
				product.setBrandCode(entity.);
				productList.add(product);
			}
			xeVenPurchSupProductWriteMapper.insertProductBatch(productList);
		}*/
		return map;  
	}
	
	/**
	 * 确认非集采采购单是否发货
	 * @author: 李书峰
	 * @createTime: 2018年3月2日 下午4:45:16  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return XeVenPurchForm
	 */
	@Override
	public XeVenPurchForm sendGoodsIsFinish(XeVenPurchForm xeVenPurchForm) {
		//集采异常完成&&整柜手动创建关联销单全部已发货
		if(VenPurchTypeEnum.ALLOT_BUY.getValue().equals(xeVenPurchForm.getPurchType())){
			Map<String,Object> parms = new HashMap<String,Object>();
			parms.put("purchOrder", xeVenPurchForm.getPurchOrder());
			parms.put("userCode", xeVenPurchForm.getUserCode());
			//查询是否有订单没有发货，有的话直接提示
			int orderSendedNum = 0;
			orderSendedNum = xeVenPurchOrderReadMapper.querySendOrderNums(parms);
			if( orderSendedNum > 0 ){
				xeVenPurchForm.setDelFlag(5);
				return xeVenPurchForm;
			}
			List<XeVenPurchProductView> productList = xeVenPurchOrderReadMapper.queryPurchProductList(parms);
			List<XeVenPurchProductView> detailList = xeVenPurchOrderReadMapper.queryPurchArriveProductList(parms);
			int sendResult = 0;
			if( null != productList && productList.size() > 0
				&& null != detailList && detailList.size() > 0){
				//只要一个商品采购数量和收货数量不相等，该采购单即异常完成
				for(XeVenPurchProductView product : productList){
					for(XeVenPurchProductView view : detailList){
						if(null != view 
						    && null != product 
							&& null != product.getProNum()
							&&(product.getProNum().compareTo(new BigDecimal(0)) > 0)
						    && null != view.getArriveNum()
							&&(product.getProNum().compareTo(view.getArriveNum()) == 0)){
							sendResult = 0;
						}else if(null != view 
						    && null != product 
							&& null != product.getProNum()
							&&(product.getProNum().compareTo(new BigDecimal(0)) == 0)){
							sendResult = 0;
						}else{
							sendResult = 1;
							break;
						}
					}
				}
			}else if(null != productList && productList.size() > 0
					&& (null == detailList || detailList.size() == 0)){
				sendResult = 1;
			}
			if( sendResult == 0 ){
				xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.NORMAL_COMPLETE.getValue());
			}else{
				xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
			}
		}else if(VenPurchTypeEnum.LARGE_BUY.getValue().equals(xeVenPurchForm.getPurchType())){//集采的在采购收货入库时正常完成，页面上异常完成。
			xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
		}
		return xeVenPurchForm;  
	}	
	
	/**
	 * 确认完成采购单
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:42:48  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int finishPurchOrder(XeVenPurchForm xeVenPurchForm) throws Exception {
		log.info("========XeVenPurchService.finishPurchOrder() start==purchOrder:" + xeVenPurchForm.getPurchOrder() + "======");
		//更新采购单结果
		int resultfinish = 0;
		//判空
		if (null == xeVenPurchForm)
			return resultfinish;
//		//确认条件（集采异常完成&&整柜手动创建关联销单全部已发货）
//		if(VenPurchTypeEnum.RETAIL_BUY.getValue().equals(xeVenPurchForm.getPurchType())){
//			
//			if(){
//				xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.NORMAL_COMPLETE.getValue());
//			}else{
//				xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
//			}
//		}else if(VenPurchTypeEnum.LARGE_BUY.getValue().equals(xeVenPurchForm.getPurchType())){//集采的在采购收货入库时正常完成，页面上异常完成。
//			xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
//		}
		//更新审核状态和采购状态
		Date date = new Date();
		XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
		purchEntity.setPurchStatus(xeVenPurchForm.getPurchStatus());
		purchEntity.setCompleteDate(date);
		purchEntity.setVersion(xeVenPurchForm.getVersion());
		purchEntity.setModifyUser(xeVenPurchForm.getModifyUser());
		purchEntity.setUserCode(xeVenPurchForm.getUserCode());
		List<String> purchOrderList = new ArrayList<String>();
		purchOrderList.add(xeVenPurchForm.getPurchOrder());
		purchEntity.setPurchOrderList(purchOrderList);
		resultfinish = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
		
		String userCode = xeVenPurchForm.getUserCode();
		String userName = xeVenPurchForm.getModifyUser();
		Map<String,Object> mapParms = new HashMap<String,Object>();
		mapParms.put("userCode",userCode);
		mapParms.put("purchOrderList", purchOrderList);
		List<XeVenPurchOrderEntity> purchList = xeVenPurchOrderWriteMapper.queryPurchDetail(mapParms);
		List<XeVenPurchOrderDetailEntity> detailList = xeVenPurchOrderDetailWriteMapper.queryPurchProductListForFin(mapParms);
		
		if(xeVenPurchForm.getPurchType() != null 
			&& !VenPurchTypeEnum.RETAIL_BUY.getValue().equals(xeVenPurchForm.getPurchType())
			&& VenAddTypeEnum.MANUAL.getValue().equals(xeVenPurchForm.getAddType())
			&& null != purchList && purchList.size() > 0 
			&& null != detailList && detailList.size() > 0 ){
			log.info("========更新库存======");
			//封装库存一览数据
			List<XeVenStoreInventoryEntity> list = new ArrayList<XeVenStoreInventoryEntity>();
			for(XeVenPurchOrderDetailEntity entity:detailList){
				XeVenStoreInventoryEntity record = new  XeVenStoreInventoryEntity();
				record.setUserCode(userCode);
				
				/**  完成时，把采购单的采购在途数减去  要释放的采购在途数为 购买数-已收货数*/
				BigDecimal arriveNum = new BigDecimal(0);
				BigDecimal proNum = entity.getProNum();
				BigDecimal transitNum = proNum.subtract(arriveNum);
				BigDecimal tInv = transitNum.multiply(new BigDecimal(-1));
				record.setTransitInv(tInv.setScale(2, BigDecimal.ROUND_HALF_UP));
				record.setModifyUser(userName);
				XeVenPurchOrderEntity purch = purchList.get(0);
				record.setStoreId(purch.getStoreId());
				record.setProSku(entity.getProSku());
				list.add(record);
			}
			xeVenStoreInventoryWriteMapper.batchUpdateStoreInv(list);
		}
		/**
		 * 2017/11/1 11:11
		 * 毕总需求更改，应付款单改到发货时生成
		 */
		//零采和分拨生成应付款单
		//一期应付款单只生成零采的
		//一期二版改成零采+分拨
		if( null != purchList && purchList.size() > 0 
				&& null != detailList && detailList.size() > 0 
				&& VenPurchTypeEnum.RETAIL_BUY.getValue().equals(xeVenPurchForm.getPurchType())){
			log.info("========新增应付款单======");
			Map<String,String> mapFin = new HashMap<String,String>();//批量时保证一个采购多个订单只生成一个应付款单
			Map<String,String> sendTimeMap = new HashMap<String,String>();
			for(XeVenPurchOrderEntity purch : purchList ){
				if(mapFin.containsKey(purch.getPurchOrder())){
					String value = mapFin.get(purch.getPurchOrder()).toString();
					mapFin.put(purch.getPurchOrder(), value+","+purch.getOrderId());
				}else{
					mapFin.put(purch.getPurchOrder(), purch.getOrderId());
				}
				sendTimeMap.put(purch.getPurchOrder(), purch.getSendTime());
			}
			if(null != mapFin
				&& mapFin.size() > 0){
				List<XeVenFinPurchPayEntity> payList = new ArrayList<XeVenFinPurchPayEntity>();
				Map<String,String> purPayMap = new HashMap<String,String>();
				for(XeVenPurchOrderEntity purch : purchList ){
					if(purPayMap.containsKey(purch.getPurchOrder())){
						continue;
					}
					XeVenFinPurchPayEntity fi = new XeVenFinPurchPayEntity();
					fi.setUserCode(userCode);//用户编码
					fi.setpSettleCode(StoreHouseSeqUtil.seqUtils.createFinPurchCode());//付款单号
					fi.setPurchId(purch.getPurchOrder());//采购单号
					fi.setOrderId(mapFin.get(purch.getPurchOrder()));//订单号
					fi.setpSettleStatus(1);
					fi.setRejectStatus(1);
					fi.setCreateUser(userName);
					fi.setDelFlag(VenDelEnum.NO.getValue());
					fi.setFinType(1);
					fi.setSendTime(sendTimeMap.get(purch.getPurchOrder()));
					payList.add(fi);
					purPayMap.put(purch.getPurchOrder(), fi.getpSettleCode());
				}
				if(null != payList && payList.size() > 0 ){
					xeVenFinPurchPayReadService.insertBatchFinPurchPay(payList);
				}
				
				List<XeVenFinPurchPayDetailEntity> finPurchPayDetailList = new ArrayList<XeVenFinPurchPayDetailEntity>();
				for(XeVenPurchOrderDetailEntity entity : detailList){
					if(!purPayMap.containsKey(entity.getPurchOrder())){
						continue;
					}
					XeVenFinPurchPayDetailEntity detail = new XeVenFinPurchPayDetailEntity();
					detail.setpSettleCode(purPayMap.get(entity.getPurchOrder()));//付款单号
					detail.setProSku(entity.getProSku());
					detail.setProName(entity.getProName());
					detail.setProNum(entity.getProNo());
					detail.setSpecName(entity.getSpecName());
					detail.setSpecValue(entity.getSpecValue());
					detail.setPricingType(entity.getPriceType());
					detail.setProUnit(entity.getProUnit());
					detail.setPurchNum(entity.getProNum());
					detail.setBuyPrice(entity.getBuyPrice());//进货价
					detail.setPurchPrice(entity.getProAmount());//采购单价*采购数量
					detail.setProOrgCode(entity.getCategoryCode());
					detail.setProOrgCodeName(entity.getCategoryName());
					detail.setRealSendNum(entity.getRealSendNum());
					detail.setProCostPrice(entity.getProCostPrice());
					detail.setProTotalPrice(entity.getProTotalPrice());
					detail.setProPrice(entity.getProPrice());
//					detail.setProPayAmount(entity.getProPayAmount());
					BigDecimal rea = com.xebest.common.util.XeBaseUtil.baseUtil.calSendAmt(
							entity.getPurchaseNum(),
							entity.getRealSendNum(), 
							entity.getProTotalPrice(),
							entity.getPmtAmount());

					detail.setProPayAmount(rea);
					
					detail.setDifferenceRefAmount(entity.getDifferenceAmount());
					detail.setPmtAmount(entity.getPmtAmount());
					detail.setPlatPmtAmount(entity.getPlatPmtAmount());
					finPurchPayDetailList.add(detail);
				}
				if(null != finPurchPayDetailList && finPurchPayDetailList.size() > 0 ){
					xeVenFinPurchPayReadService.insertBatchFinPurchPayDetail(finPurchPayDetailList);
					log.info("========新增应付款单结束======");
				}
			}
		}
		log.info("========XeVenPurchService.finishPurchOrder() end==purchOrder:" + xeVenPurchForm.getPurchOrder() + "======");
		log.debug("采购单更新结果："+resultfinish);
		return resultfinish ;  
	}
	
	/**
	 * 更新采购单状态为已完成
	 * @author: 杜春静  
	 * @createTime: 2017年8月28日 上午10:10:45  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return
	 * @throws Exception int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int updatePurchOrderToFinish(XeVenPurchForm xeVenPurchForm) throws Exception {
		//更新采购单结果
		int resultfinish = 0;
		//判空
		if (null == xeVenPurchForm) 
			return resultfinish;
		/*此处添加确认条件，调仓储接口*/
		//更新审核状态和采购状态
		Date date = new Date();
		XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
		purchEntity.setPurchStatus(xeVenPurchForm.getPurchStatus());
		purchEntity.setCompleteDate(date);
		purchEntity.setVersion(xeVenPurchForm.getVersion());
		purchEntity.setModifyUser(xeVenPurchForm.getModifyUser());
		purchEntity.setUserCode(xeVenPurchForm.getUserCode());
		List<String> purchOrderList = new ArrayList<String>();
		purchOrderList.add(xeVenPurchForm.getPurchOrder());
		purchEntity.setPurchOrderList(purchOrderList);
		resultfinish = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
		
		log.debug("采购单更新结果："+resultfinish);
		/*此处添加确认进一步操作，调仓储和财务接口*/
		return resultfinish ;  
	}
	
	/**
	 * 查询采购单列表
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:29:24  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return List<XeVenPurchView>
	 */
	@Override
	public List<XeVenPurchView> queryPurchList(XeVenPurchForm xeVenPurchForm) {
		//组装参数
		XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
		if(null != xeVenPurchForm ){
			purchEntity = JSONObject.parseObject(JSONObject.toJSONString(xeVenPurchForm), XeVenPurchOrderEntity.class);
			
			if(null != xeVenPurchForm.getSearchType()
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchText())){
				if(new Integer(1).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setPurchOrder(xeVenPurchForm.getSearchText());
				}else if(new Integer(2).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setSupplierName(xeVenPurchForm.getSearchText());
				}else if(new Integer(3).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setRemark(xeVenPurchForm.getSearchText());
				}else if(new Integer(4).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setStoreName(xeVenPurchForm.getSearchText());
				}else if(new Integer(5).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setOrderIdSearch(xeVenPurchForm.getSearchText());
				}
			}
			
			if(null != xeVenPurchForm.getSearchTimeType()
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchTimeStart())
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchTimeEnd())){
				if(new Integer(1).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setSignDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setSignDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}else if(new Integer(2).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setExpectedArrivalDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setExpectedArrivalDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}else if(new Integer(3).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setCompleteDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setCompleteDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}
			}
		}
		//查询参数 
//		purchEntity.setUserCode("mc023f29ce9cd4b8");
		List<XeVenPurchView> purchOrderList = xeVenPurchOrderReadMapper.queryPurchByParm(purchEntity);  
		for(XeVenPurchView vie : purchOrderList){
			XeVenStoreReceiptForm form = new XeVenStoreReceiptForm();
			form.setRelationOrder(vie.getPurchOrder());
			Map<String, Object>  map = new HashMap<String, Object>();
			map.put("form", form);
			List<XeVenStoreReceiptView>  list = receiptReadMapper.listStoreReceiptByParam(map);
			if(list.size()>0){
				vie.setCancelFlag(1);
			}else{
				vie.setCancelFlag(2);
			}
		}
		return purchOrderList;  
	}
	
	/**
	 * 查询采购单详情
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:33:33  
	 * @history:
	 * @param xeVenPurchForm
	 * @return XeVenPurchView
	 */
	@Override
	public XeVenPurchView queryPurchDetail(XeVenPurchForm xeVenPurchForm) {
		//组装参数
		Map<String,Object> map = new HashMap<String,Object>();
//		map.put("userCode", "SH170817138277");
		map.put("userCode", xeVenPurchForm.getUserCode());
		map.put("purchOrder", xeVenPurchForm.getPurchOrder());
		//采购单
		XeVenPurchView purch = xeVenPurchOrderReadMapper.queryPurchDetail(map);
		if(null != purch){
			//采购商品列表
			purch.setUserCode(xeVenPurchForm.getUserCode());
			purch.setPurchOrder(xeVenPurchForm.getPurchOrder());
			purch = getAmount(purch);
			//采购单据
			XeVenPurchOrderBillEntity bill = new XeVenPurchOrderBillEntity();
			bill.setPurchOrder(xeVenPurchForm.getPurchOrder());
			List<XeVenPurchOrderBillView> bills = xeVenPurchOrderReadMapper.queryPurchBills(bill);
			purch.setBillList(bills);
		}
		return purch;
	}
	
	/**
	 * 查询采购单商品
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:44:18  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return List<>
	 */
	@Override
	public List<XeVenPurchProductView> queryPurchProducts(XeVenPurchForm xeVenPurchForm) {
		//组装参数
		Map<String,Object> map = new HashMap<String,Object>();
		String purchOrder = xeVenPurchForm.getPurchOrder();
		map.put("userCode", xeVenPurchForm.getUserCode());
		map.put("purchOrder", purchOrder);
		map.put("orderId", xeVenPurchForm.getOrderId());
		//采购商品列表
		List<XeVenPurchProductView> products = xeVenPurchOrderReadMapper.queryPurchProductList(map);
		if(null != products && products.size() > 0 ){
			if(StringUtils.isBlank(purchOrder) ){
				purchOrder = products.get(0).getPurchOrder();
			}
		}else{
			return products;
		}
		if(VenPurchTypeEnum.LARGE_BUY.getValue().equals(xeVenPurchForm.getPurchType())){
			List<XeVenPurchProductView> arrives = xeVenPurchOrderReadMapper.queryPurchArriveProductList(map);
			if(null != products && products.size() > 0 
					&& null != arrives && arrives.size() > 0 ){
				Map<String,Object> productMap = new HashMap<String,Object>();
				for( XeVenPurchProductView arrive : arrives ){
					if(null == arrive || StringUtils.isBlank(arrive.getPurchOrder())){
						continue;
					}
					productMap.put(arrive.getPurchOrder()+"-"+arrive.getProSku(), arrive);
				}
				for( XeVenPurchProductView product : products ){
					String key = product.getPurchOrder()+"-"+product.getProSku();
					XeVenPurchProductView proSku = (XeVenPurchProductView)productMap.get(key);
					if( null != proSku ){
						product.setArriveNum(proSku.getArriveNum());
						product.setReceivedCharges(proSku.getReceivedCharges());
					}
					product.setPicUrl(StringUtils.isNotBlank(product.getPicUrl())?product.getPicUrl():null);
				}
			}
		}else{
			if(StringUtils.isNotBlank(xeVenPurchForm.getPurchOrder())
					&& null != products && products.size() > 0 ){
				List<String> skuList = new ArrayList<String>();
				for(XeVenPurchProductView product : products ){
					skuList.add(product.getProSku());
				}
				Map<String, Object> parmMap =new HashMap<String, Object>();
				parmMap.put("list", skuList);
				parmMap.put("purchOrder",xeVenPurchForm.getPurchOrder());
				List<Map<String, Object>> nums = xeVenOrderReadMapper.sumPurchase(parmMap);
				Map<String,Object> mm = new HashMap<String,Object>();
				if( null != nums && nums.size() > 0 ){
					for( int i = 0 ; i<nums.size() ; i++ ){
						Map<String,Object> ma = nums.get(i);
						String key = ma.get("proSku").toString();
						if(null != ma.get("realSendNum") 
								&& StringUtils.isNotBlank(ma.get("realSendNum").toString())){
							mm.put(key, ma.get("realSendNum").toString());
						}
					}
				}
				for(XeVenPurchProductView product : products ){
					BigDecimal arriveNum = null;
					if(null != mm && mm.size() > 0 
							&& null != mm.get(product.getProSku())){
						arriveNum = new BigDecimal(mm.get(product.getProSku()).toString());
						product.setArriveNum(arriveNum);
						BigDecimal buyPrice = null;
						if(null != product.getBuyPrice()){
							buyPrice = product.getBuyPrice();
						}
						if(null != buyPrice && null != arriveNum){
							product.setReceivedCharges(buyPrice.multiply(arriveNum));
						}
					}
					if( null == arriveNum){
						arriveNum = new BigDecimal(0);
						product.setArriveNum(arriveNum);
						product.setReceivedCharges(arriveNum);
					}
					product.setPicUrl(StringUtils.isNotBlank(product.getPicUrl())?product.getPicUrl():null);
				}
			}
		}	
		return products;
	}
	
	/**
	 * 查询采购单商品
	 * @author: 李书峰
	 * @createTime: 2017年6月21日 下午3:44:18  
	 * @history:  
	 * @param xeVenPurchForm
	 * @return List<>
	 */
	@Override
	public Map<String,Object> queryReceiptDetail(XeVenPurchForm xeVenPurchForm) {
		
		Map<String,Object> resultMap = new HashMap<String,Object>();		
		//采购详情
		XeVenPurchOrderEntity entity = new XeVenPurchOrderEntity();
		entity.setUserCode(xeVenPurchForm.getUserCode());
		entity.setPurchOrder(xeVenPurchForm.getPurchOrder());
		List<XeVenPurchView> purchs = xeVenPurchOrderReadMapper.queryPurchByParm(entity);
		XeVenPurchView purch = null;
		if( null != purchs && purchs.size() > 0 ){
			purch = purchs.get(0);
			purch.setCreateUser(xeVenPurchForm.getModifyUser());
		}
		purch.setUserCode(xeVenPurchForm.getUserCode());
		purch.setPurchOrder(xeVenPurchForm.getPurchOrder());
		purch = getAmount(purch);
		resultMap.put("purch", purch);
		
		//采购商品列表
		List<XeVenPurchProductView> products = purch.getPurchProductList();
		resultMap.put("products", products);
		
		//供货商明细
		XeVenPurchSupInfoEntity supplierEntity = new XeVenPurchSupInfoEntity();
		supplierEntity.setSupplierCode(purch.getSupplierCode());
		supplierEntity.setUserCode(purch.getUserCode());
//		supplierEntity.setUserCode("SH170712925781");
		List<XeVenPurchSupInfoView> supList = xeVenPurchSupInfoReadMapper.selectSupplier(supplierEntity);
		XeVenPurchSupInfoView supplier = null != supList && supList.size() > 0 ? supList.get(0) : null ;
		resultMap.put("supplier", supplier);
		return resultMap;
	}
	 
	private XeVenPurchView getAmount(XeVenPurchView purch){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userCode", purch.getUserCode());
		map.put("purchOrder", purch.getPurchOrder());
		List<XeVenPurchProductView> products = xeVenPurchOrderReadMapper.queryPurchProductList(map);
		if( null == products || products.size() == 0 ){
			return purch;
		}
		List<XeVenPurchProductView> arrives = xeVenPurchOrderReadMapper.queryPurchArriveProductList(map);
		BigDecimal totalAmount = new BigDecimal(0);
		if(VenPurchTypeEnum.LARGE_BUY.getValue().equals(purch.getPurchType())){
			if( null != products && products.size() > 0 
					&& null != arrives && arrives.size() > 0 ){
				Map<String,Object> productMap = new HashMap<String,Object>();
				for( XeVenPurchProductView arrive : arrives ){
					if(null == arrive || StringUtils.isBlank(arrive.getPurchOrder())){
						continue;
					}
					productMap.put(arrive.getPurchOrder()+"-"+arrive.getProSku(), arrive);
				}
				for( XeVenPurchProductView product : products ){
					String key = product.getPurchOrder()+"-"+product.getProSku();
					XeVenPurchProductView proSku = (XeVenPurchProductView)productMap.get(key);
					if( null != proSku ){
						product.setArriveNum(proSku.getArriveNum());
						product.setReceivedCharges(proSku.getReceivedCharges());
					}
					product.setPicUrl(StringUtils.isNotBlank(product.getPicUrl())? product.getPicUrl():null);
				}
			}
		}else{
			List<String> skuList = new ArrayList<String>();
			for(XeVenPurchProductView product : products ){
				skuList.add(product.getProSku());
			}
			Map<String, Object> parmMap =new HashMap<String, Object>();
			parmMap.put("list", skuList);
			parmMap.put("purchOrder", purch.getPurchOrder());
			List<Map<String, Object>> nums = xeVenOrderReadMapper.sumPurchase(parmMap);
			Map<String,Object> mm = new HashMap<String,Object>();
			if( null != nums && nums.size() > 0 ){
				for( int i = 0 ; i<nums.size() ; i++ ){
					Map<String,Object> ma = nums.get(i);
					String key = ma.get("proSku").toString();
					if(null != ma.get("realSendNum") 
							&& StringUtils.isNotBlank(ma.get("realSendNum").toString())){
						mm.put(key, ma.get("realSendNum").toString());
					}
				}
			}
			for(XeVenPurchProductView product : products ){
				BigDecimal aa = new BigDecimal(0);
				if(null != mm.get(product.getProSku()) && StringUtils.isNotBlank(mm.get(product.getProSku()).toString())){
					aa = new BigDecimal(mm.get(product.getProSku()).toString());
					product.setArriveNum(aa);
					BigDecimal buyPrice = product.getBuyPrice();
					BigDecimal proAmount = buyPrice.multiply(aa);
					totalAmount = totalAmount.add(proAmount);
					product.setReceivedCharges(proAmount);
				}
			}
			purch.setArriveAmount(totalAmount);
		}
		purch.setPurchProductList(products);
		return purch;
	}
	
	/**
     * 
     * @author: 李书峰
     * @createTime: 2017年9月14日 下午4:03:21  
     * @history:  
     * @param map
     * @return Map<String,Object>
     */
	@Override
	public BigDecimal queryWaitDealPurchOrderNum(Map<String, Object> map) {
		return xeVenPurchOrderReadMapper.queryWaitDealPurchOrderNum(map); 
	}
	
    /**
     * 
     * @author: 李书峰
     * @createTime: 2017年9月14日 下午4:03:21  
     * @history:  
     * @param map
     * @return Map<String,Object>
     */
	@Override
	public BigDecimal queryMonthPurchAmount(Map<String, Object> map) {
		return xeVenPurchOrderReadMapper.queryMonthPurchAmount(map); 
	}

	/**
	 * 查询订单汇总页面订单汇总采购单
	 * @author RCZ
	 * @param form
	 * @return
	 */
	@Override
	public List<XeVenSumPurchView> querySummaryPurch(XeVenPurchForm form) {
		List<XeVenSumPurchView> list = this.xeVenPurchOrderReadMapper.querySummaryPurch(form);
		if (null == list || list.size() == 0) {
			return list;
		}
		for (int i = 0; i < list.size(); i++) {
			XeVenSumPurchView xeVenSumPurchView =  list.get(i);
			List<XeVenSummaryPurchView> sumPurchViewList = xeVenPurchOrderReadMapper.queryPurchDetailByParam(xeVenSumPurchView);
			xeVenSumPurchView.setPurchList(sumPurchViewList);
		}
		return list;
	}
	
	/**
	 * @Description: 鲜易云管理平台采购单管理-----查询采购单列表
	 * @author: 袁世林
	 * @createTime: 2018年6月19日 下午2:23:37   
	 * @param: form       
	 * @return: List<XeVenPurchView>
	 */
	@Override
	public List<XeVenPurchView> queryPurchListRestApi(XeVenPurchForm xeVenPurchForm) {

		//组装参数
		XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
		if(null != xeVenPurchForm ){
			purchEntity = JSONObject.parseObject(JSONObject.toJSONString(xeVenPurchForm), XeVenPurchOrderEntity.class);
			
			if(null != xeVenPurchForm.getSearchType()
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchText())){
				if(new Integer(1).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setPurchOrder(xeVenPurchForm.getSearchText());
				}
				else {
					purchEntity.setOrderId(xeVenPurchForm.getSearchText());
				}
			}
			
			/*if(null != xeVenPurchForm.getSearchParamType()
					&& StringUtils.isNotBlank(xeVenPurchForm.getSearchParamText())){
					if(new Integer(1).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setUserName(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(2).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setShopName(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(3).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setUserCode(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(4).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setSupplierName(xeVenPurchForm.getSearchParamText());
					}
				}*/
			if(null != xeVenPurchForm.getSearchParamType()
					&& StringUtils.isNotBlank(xeVenPurchForm.getSearchParamText())){
					if(new Integer(1).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setUserCode(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(2).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setSupplierName(xeVenPurchForm.getSearchParamText());
					}
				}
			
			if(null != xeVenPurchForm.getSearchTimeType()
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchTimeStart())
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchTimeEnd())){
				if(new Integer(1).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setSignDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setSignDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}else if(new Integer(2).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setExpectedArrivalDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setExpectedArrivalDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}else if(new Integer(3).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setCompleteDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setCompleteDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}
			}
			else
			{
				//没有根据时间查询的话查询当天的
				purchEntity.setSendTime(DateUtil.getDefaultDate ());
			}
			/*else if (xeVenPurchForm.getProNum() != null)
			{	//导出时：没有根据时间查询的话查询当天的
				purchEntity.setSendTime(DateUtil.getDefaultDate ());
			}*/
		}
		//查询参数
		List<XeVenPurchView> purchOrderList = xeVenPurchOrderReadMapper.queryPurchByParmRestApi(purchEntity);  
		
		for (XeVenPurchView purchView : purchOrderList)
		{
			String venName = xeBaseUtil.getVenName(purchView.getUserCode()) ;
			String shopName = xeBaseUtil.getVenShopName(purchView.getUserCode()) ;
			
			purchView.setUserName(venName);
			purchView.setShopName(shopName);
		}
		
		return purchOrderList;  
	}
	  
	
	/**
	 * @Description: 鲜易云管理平台采购单管理-----查询采购单详情
	 * @author: 袁世林
	 * @createTime:   2018年6月19日 下午6:50:35   
	 * @param: xeVenPurchForm
	 * @return: XeVenPurchView
	 */
	@Override
	public XeVenPurchView queryPurchDetailRestApi(XeVenPurchForm xeVenPurchForm) {
		//组装参数
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("purchOrder", xeVenPurchForm.getPurchOrder());
		//采购单
		XeVenPurchView purch = xeVenPurchOrderReadMapper.queryPurchDetailRestApi(map);
		if(null != purch){
			String venName = xeBaseUtil.getVenName(purch.getUserCode()) ;
			purch.setUserName(venName);
			String shopName = xeBaseUtil.getVenShopName(purch.getUserCode()) ;
			purch.setShopName(shopName);
			//采购商品列表
			purch.setPurchOrder(xeVenPurchForm.getPurchOrder());
			purch = getAmount(purch);
			//采购单据
			XeVenPurchOrderBillEntity bill = new XeVenPurchOrderBillEntity();
			bill.setPurchOrder(xeVenPurchForm.getPurchOrder());
			List<XeVenPurchOrderBillView> bills = xeVenPurchOrderReadMapper.queryPurchBills(bill);
			purch.setBillList(bills);
		}
		return purch;
	}
	
	/**
	 * @Description: 导出采购单详情列表
	 * @author: 袁世林
	 * @createTime: 2018年6月24日 下午4:59:01   
	 * @param: form
	 * @return: List<XeVenPurchView>
	 */
	@Override
	public List<XeVenPurchView> exportPurchDetail(XeVenPurchForm xeVenPurchForm) {
		
		//组装参数
		XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
		if(null != xeVenPurchForm ){
			purchEntity = JSONObject.parseObject(JSONObject.toJSONString(xeVenPurchForm), XeVenPurchOrderEntity.class);
			
			if(null != xeVenPurchForm.getSearchType()
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchText())){
				if(new Integer(1).equals(xeVenPurchForm.getSearchType())){
					purchEntity.setPurchOrder(xeVenPurchForm.getSearchText());
				}
				else {
					purchEntity.setOrderId(xeVenPurchForm.getSearchText());
				}
			}
			
			/*if(null != xeVenPurchForm.getSearchParamType()
					&& StringUtils.isNotBlank(xeVenPurchForm.getSearchParamText())){
					if(new Integer(1).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setUserName(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(2).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setShopName(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(3).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setUserCode(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(4).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setSupplierName(xeVenPurchForm.getSearchParamText());
					}
				}*/
			
			if(null != xeVenPurchForm.getSearchParamType()
					&& StringUtils.isNotBlank(xeVenPurchForm.getSearchParamText())){
					if(new Integer(1).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setUserCode(xeVenPurchForm.getSearchParamText());
					}else if(new Integer(2).equals(xeVenPurchForm.getSearchParamType())){
						purchEntity.setSupplierName(xeVenPurchForm.getSearchParamText());
					}
				}
			
			if(null != xeVenPurchForm.getSearchTimeType()
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchTimeStart())
				&& StringUtils.isNotBlank(xeVenPurchForm.getSearchTimeEnd())){
				if(new Integer(1).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setSignDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setSignDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}else if(new Integer(2).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setExpectedArrivalDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setExpectedArrivalDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}else if(new Integer(3).equals(xeVenPurchForm.getSearchTimeType())){
					purchEntity.setCompleteDateStart(xeVenPurchForm.getSearchTimeStart());
					purchEntity.setCompleteDateEnd(xeVenPurchForm.getSearchTimeEnd());
				}
			}
			else
			{
				//没有根据时间查询的话查询当天的
				purchEntity.setSendTime(DateUtil.getDefaultDate ());
			}
		}
		//查询参数
		List<XeVenPurchView> purchOrderList = xeVenPurchOrderReadMapper.queryPurchByParmRestApi(purchEntity);  
		
		List<XeVenPurchView> resultPurchOrderList = new ArrayList<>() ; 
		for (XeVenPurchView purchView : purchOrderList)
		{
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("purchOrder", purchView.getPurchOrder());
			//采购单
			XeVenPurchView purch = xeVenPurchOrderReadMapper.queryPurchDetailRestApi(map);
			
			if(null != purch){
				String venName = xeBaseUtil.getVenName(purch.getUserCode()) ;
				purch.setUserName(venName);
				String shopName = xeBaseUtil.getVenShopName(purch.getUserCode()) ;
				purch.setShopName(shopName);
				
				
				//采购商品列表
				purch = getAmount(purch);
				//采购单据
				/*XeVenPurchOrderBillEntity bill = new XeVenPurchOrderBillEntity();
				bill.setPurchOrder(xeVenPurchForm.getPurchOrder());
				List<XeVenPurchOrderBillView> bills = xeVenPurchOrderReadMapper.queryPurchBills(bill);
				purch.setBillList(bills);*/
			}
			
			resultPurchOrderList.add(purch) ;
		}
		
		return resultPurchOrderList ;
	}

	/**
	 * 采购订单中某商品被占用数量
	 *
	 * @param spu 商品的spu
	 * @return spu在采购单中呗占用的采购单数
	 * @author zhouys
	 */
	@Override
	public int spuTakeUpCount(String spu) {
		return xeVenPurchOrderReadMapper.spuTakeUpCount(spu);
	}

	@Override
	public int cancelFinanceCheck(XeVenPurchForm form) throws Exception {
		int res = 0;
		//1.更新采购状态
		List<String> purchOrders = new ArrayList<String>();
		purchOrders.add(form.getPurchOrder());
		XeVenPurchOrderEntity purchEntity = new XeVenPurchOrderEntity();
		purchEntity.setPurchOrderList(purchOrders);
		purchEntity.setCheckStatus(1);
		purchEntity.setPurchStatus(2);
		res = xeVenPurchOrderWriteMapper.updatePurch(purchEntity);
		//2.回退库存更新库存
		//查询采购相关数据
		Map<String,Object> mapParms = new HashMap<String,Object>();
		String userCode = form.getUserCode();
		mapParms.put("userCode",userCode);
		mapParms.put("purchOrderList", purchOrders);
		List<XeVenPurchOrderEntity> purchList = xeVenPurchOrderWriteMapper.queryPurchDetail(mapParms);
		List<XeVenPurchOrderDetailEntity> detailList = xeVenPurchOrderDetailWriteMapper.queryPurchProductList(mapParms);
		//财务审核之后库存初始化集采商品，因为集采商品可能不存在
		if(VenPurchCheckEnum.CHECKED.getValue().equals(purchList.get(0).getCheckStatus())
			&& VenPurchStatusEnum.PURCHING.getValue().equals(purchList.get(0).getPurchStatus())){
			//更新采购在途数
			if( null != purchList && purchList.size() > 0 
				&& null != detailList && detailList.size() > 0){
				for(XeVenPurchOrderEntity purch : purchList ){
					//零采整柜不要更新 
					if(!VenPurchTypeEnum.LARGE_BUY.getValue().equals(purch.getPurchType())){
						continue;
					}
					for(XeVenPurchOrderDetailEntity entity : detailList){
						XeVenStoreInventoryEntity storeInventory = new XeVenStoreInventoryEntity();
						storeInventory.setUserCode(userCode);
						storeInventory.setStoreId(purch.getStoreId());
						storeInventory.setProSku(entity.getProSku());
						storeInventory.setTransitInv(entity.getProNum().multiply(new BigDecimal("-1")));
						res = xeVenStoreInventoryService.initStoreInv(storeInventory);
					}
				}
			}
			
		}
		return res;
	}
	
}
  
